#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->initThread();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::initThread()
{
    //main
    qDebug()<<"Widget主线程号:"<<QThread::currentThread();

    //QThreadRun
    m_QThreadRun = new QThreadRun();

    //QMoveToThread
    m_QThread = new QThread(this);
    m_QMoveToThread = new QMoveToThread();
    connect(this,SIGNAL(signal_moveToThread()),m_QMoveToThread,SLOT(slot_moveToThread()),Qt::UniqueConnection);
    m_QMoveToThread->moveToThread(m_QThread);

    //QRunnableRun
    m_QThreadPool = new QThreadPool();
    m_QThreadPool->setMaxThreadCount(3);   //设置非全局线程池可容纳线程个数为3个
    m_QRunnableRun = new QRunnableRun();

    //QtConcurrentRun
    startFlag = false;
    //qDebug()<<QThreadPool::globalInstance()->maxThreadCount();   //获取全局线程池最大线程个数
    //QThreadPool::globalInstance()->setMaxThreadCount(10);        //设置全局线程池可容纳线程个数

}

void Widget::setSwitch(bool flag)
{
    startFlag = flag;
}

void Widget::myQtConcurrentRun()
{
    while(startFlag)
    {
        qDebug()<<"QtConcurrent子线程号"<<QThread::currentThread();
        QThread::msleep(1000);
    }
}

void Widget::myMainRun()
{
    while(startFlag)
    {
        qDebug()<<"当前线程号："<<QThread::currentThread();
        QThread::msleep(1000);
    }
}

//QThreadRun
void Widget::on_pb_start_clicked()
{
    m_QThreadRun->setSwitch(true);
    m_QThreadRun->start();
}

void Widget::on_pb_stop_clicked()
{
    m_QThreadRun->setSwitch(false);
}

//QMoveToThread
void Widget::on_pb_start_2_clicked()
{
    m_QThread->start();
    m_QMoveToThread->setSwitch(true);
    //m_QMoveToThread->slot_moveToThread();   不能直接调用处理函数,函数还是在主线程中运行
    emit signal_moveToThread();   //发送信号启动子线程处理函数
}

void Widget::on_pb_stop_2_clicked()
{
    m_QMoveToThread->setSwitch(false);
}

//QRunnableRun
void Widget::on_pb_start_3_clicked()
{
    m_QRunnableRun->setSwitch(true);

    //全局线程池方式
    //QThreadPool::globalInstance()->start(m_QRunnableRun);
    //qDebug()<<"全局线程池当前线程数:"<<QThreadPool::globalInstance()->activeThreadCount();   //当前活动的线程个数

    //非全局线程池方式
    m_QThreadPool->start(m_QRunnableRun);
    qDebug()<<"非全局线程池当前线程数:"<<m_QThreadPool->activeThreadCount();   //当前活动的线程个数

}

void Widget::on_pb_stop_3_clicked()
{
    m_QRunnableRun->setSwitch(false);
}

//QtConcurrentRun
void Widget::on_pb_start_4_clicked()
{
    setSwitch(true);
    QtConcurrent::run(this,&Widget::myQtConcurrentRun);
    qDebug()<<"QtConcurrentRun当前线程数:"<<QThreadPool::globalInstance()->activeThreadCount();   //当前活动的线程个数
}

void Widget::on_pb_stop_4_clicked()
{
    setSwitch(false);
}

//不使用多线程的对比测试,界面卡死
void Widget::on_pb_test_clicked()
{
    setSwitch(true);
    myMainRun();
}
